/*
 * FOF基金筛选模块
 */
require('!style!css!../css/fund.css');
var fundHtml = require('!html!../html/fund.html');
var common = require('./common.js');
var combination = require('./combination.js');
var loading = require('./loading.js');
var page = require('./page.js');
require('./jqPaginator.js');
var fundVue;
var fund = {
    title: ['查看已选基金', '关闭已选基金'],
    pn: 1,
    rn: 10,
    totalPage: 0,
    curAssetStrategyId: 0,
    selectedFundList: {},
    searchKey: '',
    sortType: '',
    sortName: '',
    isInitPage: false,
    currentTrendFund: null,
    changeEvent: false,
    all: 0,
    init: function () {
        page.setPage(5);
        common.initNav(3);
        $('.step').hide();
        $('#fund').html(fundHtml).show();
        this.initEvents();
        this.initCallback();
        fundVue = null;
        fund.changeEvent = false;
        this.goPage(1);
    },
    goPage: function (page, assetStrategyId) {
        loading.start();
        common.getData({
            path: 'fundFilter',
            callback: 'loadFundList',
            extra: '?key=' + fund.searchKey + '&pn=' + (page || 1) + '&rn=' + fund.rn + '&productType=' + window.configOption.productTypeId + '&fundType=' + window.configOption.fund + '&curAssetStrategyId=' + (assetStrategyId || fund.curAssetStrategyId) + '&sortType=' + fund.sortType + '&sortName=' + fund.sortName + '&all=' + fund.all
        });
    },
    initEvents: function () {
        $('#showAllFund').off().on('click', function () {
            if ($(this).attr('checked')) {
                $(this).removeAttr('checked');
                fund.all = 0;
            } else {
                $(this).attr('checked', 'checked');
                fund.all = 1;
            }
            fund.isInitPage = true;
            fund.goPage(1);
        });
        $('#fund').off();
        $('#fund').on('click', 'table .choice', function (e) {
            if ($(this).hasClass('fund-disabled')) {
                return false;
            }
            var target = $(e.target);
            if (target.hasClass('fundTrend')) {
                return false;
            }
            var isInput = target && target.is('input');
            var checkbox = $(this).find('.check input');
            var someFund = fund.getFundByFundExtCodeFromList(fundVue.fundList, $(this).attr('data-fundExtCode'));
            if (checkbox.is(':checked')) {
                if (isInput) {
                    fund.addSomeFund(someFund);
                } else {
                    checkbox.prop('checked', false);
                    fund.removeSomeFund(someFund);
                }
            } else {
                if (isInput) {
                    fund.removeSomeFund(someFund);
                } else {
                    checkbox.prop('checked', true);
                    fund.addSomeFund(someFund);
                }
            }
        });
        $('#fund').on('click', 'table .selected', function (e) {
            var target = $(e.target);
            if (target.hasClass('fundTrend')) {
                return false;
            }
            var isInput = target && target.is('input');
            var checkbox = $(this).find('.check input');
            if (!isInput && !checkbox.is(':checked')) {
                //return;
            }
            fund.removeSomeFund(fund.selectedFundList[$(this).attr('data-fundExtCode')]);
            $('#fund').find('.choice input[data-fundExtCode="' + $(this).attr('data-fundExtCode') + '"]').prop('checked', false);
        });
        $('#fundBtn').off().on('click', function () {
            fund.goSearch();
        });
        $('#fundInput').off().on('keypress', function (event) {
            if (event.keyCode == "13") {
                fund.goSearch();
            }
        });
        $('.sort').off().on('click', function () {
            $('#sortArrow').remove();
            var sortType = $(this).attr('data-sortType');
            if (sortType == 'desc') {
                fund.sortType = 'asc';
                $(this).append('<span id="sortArrow">↑</span>');
            } else if (sortType == 'asc') {
                fund.sortType = '';
            } else {
                fund.sortType = 'desc';
                $(this).append('<span id="sortArrow">↓</span>');
            }
            $(this).attr('data-sortType', fund.sortType);
            fund.sortName = $(this).attr('data-sortName');
            fund.isInitPage = true;
            fund.goPage(1);
        });
    },
    goSearch: function () {
        var inputVal = $.trim($('#fundInput').val());
        if (inputVal == fund.searchKey) {
            return;
        }
        fund.searchKey = inputVal;
        fund.isInitPage = true;
        fund.goPage(1);
    },
    addSomeFund: function (f) {
        console.log(f);
        if (this.getFundByFundExtCodeFromList(fundVue.selectedFundList, f.fundExtCode)) {
            return;
        }
        fundVue.selectedFundList.push(f);
        fund.selectedFundList[f.fundExtCode] = f;
    },
    removeSomeFund: function (f) {
        var fundList = fundVue.selectedFundList;
        var index = -1;
        $.each(fundList, function (k, v) {
            if (v.fundExtCode == f.fundExtCode) {
                index = k;
                return false;
            }
        });
        if (index > -1) {
            fundVue.selectedFundList.splice(index, 1);
            if (fundVue.selectedFundList.length == 0) {
                fundVue.userSelected = false;
                fundVue.currentTitle = fund.title[0];
            }
        }
    },
    getFundByFundExtCodeFromList: function (fundList, fundExtCode) {
        var someFund;
        $.each(fundList, function (k, v) {
            if (v.fundExtCode == fundExtCode) {
                someFund = v;
                return false;
            }
        });
        return someFund;
    },
    initCallback: function () {
        page.initSelectedParams(5);
        window['loadFundList'] = function (json) {
            var list = common.filterData(json, 'list');
            var ext = common.filterData(json, 'ext');
            var allKindAssetStrategy;
            var curAssetStrategyId;
            if (ext) {
                allKindAssetStrategy = ext.allKindAssetStrategy;
                curAssetStrategyId = ext.curAssetStrategyId;
            }
            if (list) {
                fund.totalPage = common.filterData(json, 'totalPage');
                if (fundVue) {
                    fundVue.fundList = list;
                    if (fund.curAssetStrategyId != curAssetStrategyId) {
                        fund.curAssetStrategyId = curAssetStrategyId;
                        fund.createPage();
                    } else {
                        if (fund.isInitPage) {
                            fund.isInitPage = false;
                            fund.createPage();
                        }
                    }
                    Vue.nextTick(function () {
                        loading.end();
                    });
                    return;
                }
                fundVue = new Vue({
                    el: '#fund',
                    data: {
                        userSelected: false,
                        showTitle: fund.title,
                        currentTitle: fund.title[0],
                        fundList: list,
                        selectedFundList: [],
                        assetStrategList: allKindAssetStrategy || '',
                        showTable: true
                    },
                    methods: {
                        showSelected: function () {
                            if (fundVue.selectedFundList.length == 0) {
                                return;
                            }
                            if (fundVue.userSelected) {
                                fundVue.currentTitle = fund.title[0];
                            } else {
                                fundVue.currentTitle = fund.title[1];
                            }
                            fundVue.userSelected = !fundVue.userSelected;
                        },
                        next: function () {
                            fund.next();
                        },
                        fundTrend: function (f) {
                            fund.currentTrendFund = f;
                            loading.start();
                            common.getData({
                                path: 'fundsTrend',
                                callback: 'fundsTrendResult',
                                extra: '?fundIds=' + f.fundExtCode
                            });
                        }
                    }
                });
                if (!fund.changeEvent) {
                    fund.changeEvent = true;
                    $('input[name="assetStrategyId"]').on('change', function () {
                        fund.goPage(1, $(this).val());
                    });
                }
                fund.createPage();
                Vue.nextTick(function () {
                    loading.end();
                });
            }
        };
        window['fundsTrendResult'] = function (json) {
            loading.end();
            fund.showFundTrend(json);
        };
    },
    showFundTrend: function (json) {
        common.enlargeECharts({
            json: json,
            bigJSONFunction: function (jsondata) {
                return fund.resetData(common.filterData(jsondata, 'priceList'));
            },
            text: '基金曲线图',
            precision: 4
        });
    },
    resetData: function (data) {
        var bigJSON = {};
        var dataArray = [];
        var nameArray = [fund.currentTrendFund.fundNameShort];
        $.each(data[0].priceList, function (k, v) {
            var childArray = [];
            childArray.push(v.date);
            $.each(nameArray, function (kk, vv) {
                childArray.push(data[kk].priceList[k].price);
            });
            dataArray.push(childArray);
        });
        bigJSON.dataArray = dataArray;
        bigJSON.nameArray = nameArray;
        return bigJSON;
    },
    createPage: function () {
        $.jqPaginator('#fundPage', {
            totalPages: fund.totalPage,
            visiblePages: 10,
            currentPage: 1,
            onPageChange: function (num, type) {
                console.log(type + ':' + num);
                if (type == 'init') {
                    return;
                }
                fund.goPage(num);
            }
        });
    },
    next: function () {
        console.log('next click...');
        var fundObj = $('.fund-content .selected input:checkbox:checked');
        if (fundObj.size() == 0) {
            alert('请选择至少一行数据');
            return false;
        }
        var fundCheck = $('#fund').find('.selected input[type="checkbox"]:checked');
        var fundCheckList = [];
        fundCheck.each(function () {
            fundCheckList.push(fund.selectedFundList[$(this).attr('data-fundExtCode')]);
        });
        window['fundCheckList'] = fundCheckList;
        combination.init();
    }
};
for (var key in fund) {
    if (key) {
        exports[key] = fund[key];
    }
}